<?php
namespace Common\Models;
use Common\BaseModel;
class Orders extends BaseModel
{
    public $res;
    public $key;

    public function initialize()
    {
        parent::initialize();
        $this->setSource('w_union_order');
    }



    /**
     * @func 根据用户时间获取各个平台的数据总和 自购订单数量
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     * @return array 以平台名称作为键 统计作为结果
     */
	public function getOrderCount($user_id,$start_end_time,$order_channel=''){
	    if($order_channel){
            $conditions = "user_id = ?1 AND order_create_time >= ?2 AND order_create_time < ?3 AND site = ?4";
            $parameters = array(1 => $user_id,2 => $start_end_time['start_at'],3 => $start_end_time['end_at'],4=>$order_channel);
        }else{
            $conditions = "user_id = ?1 AND order_create_time >= ?2 AND order_create_time < ?3";
            $parameters = array(1 => $user_id,2 => $start_end_time['start_at'],3 => $start_end_time['end_at']);
        }
        $count_array = $this::count(array(
            $conditions,
            "column" => "*",
            "group" => "site",
            "bind" => $parameters
        ));
	    $new_array = array();
	    foreach($count_array as $key=>$value){
            $new_array[$value['site']] = $value['rowcount'];//order_channel
        }
        return $new_array;
    }


    public function getOrderList($param,$page=1,$pageSize=10){
	    $conditions = "c.id>0";
        if( $param['commission_type']==1){//自推出单
            $conditions .= " AND c.user_id={$param['user_id']} and  c.commission_type=1";
        }else{//粉丝出单
            $conditions .= " AND c.user_id={$param['user_id']} and c.commission_type=2";
        }

		if(array_key_exists('is_free',$param) && !empty($param['is_free'])){
            $conditions .= " AND c.is_free ={$param['is_free']}";
        }

        if(array_key_exists('source',$param) && $param['source']=='xcx'){
            $conditions .= " AND c.order_channel not in('haodanku')";
        }

		if(array_key_exists('order_channel',$param) && !empty($param['order_channel'])){
            $conditions .= " AND c.order_channel ='{$param['order_channel']}'";
        }

		if(array_key_exists('date',$param) && !empty($param['date'])){
            $conditions .= " AND c.tk_create_time >='{$param['date']['start_at']} 00:00:00' AND OrderCommissions.tk_create_time <= '{$param['date']['end_at']}'";
        }

        if(array_key_exists('status',$param) && !empty($param['status'])){
            $conditions .= " AND c.order_status in({$param['status']})";
        }
        if(array_key_exists('site',$param) && !empty($param['site'])){
            $conditions .= " AND c.order_channel='{$param['site']}'";
        }
        $conditions .= ' AND c.money<>0';

        //当前页面
        $page = ($page - 1) * $pageSize;
        $phql = "SELECT o.id,o.user_id,o.order_id,o.order_status,o.goods_name,o.goods_id,o.goods_pic,
                o.site,o.price,o.pay_money,o.commition,o.income_rate,o.order_create_time,o.order_paid_time,
                o.order_earning_time,o.is_settlement,c.money,c.money_plus,c.commission_type,
                c.is_free,o.order_id
                FROM w_order_commissions as c LEFT JOIN `w_union_order` as o ON o.order_id = c.order_id
				where  ".$conditions ."  GROUP BY o.user_id,
	            o.order_id  order by o.order_create_time DESC LIMIT $page,$pageSize";
        $rows=$this->getDI()->get('dbSlave')->fetchAll($phql);
        return $rows;
    }



    /**
     * 查询我的订单数数量
     */
    public function getSelfOrders($user_id){
        $conditions = "user_id = ?1";
        $parameters = array(1 => $user_id);
        $count_array = $this :: count(array(
            $conditions,
            "column" => "*",
            "bind" => $parameters
        ));
        return $count_array;
    }
	public function find_back_order($order_id,$user_id,$type){
		$conditions = "order_id = '$order_id' and user_id = '0'";
		$res=$this->findFirst($conditions);
		if($res){
			if($type=='find'){
			return $res->toarray();
			}
			$res->user_id=$user_id;
			$res->is_calculation_money=0;
			$res->remark=date('Y-m-d H:i:s').'找回订单';
			$res->save();

			return $res->toarray();
		}
		return false;
	
	}


    /*
     * 我的直推今日下单人数
     * group 是否进行分组查询
     */
    public function referer_today_order($data=[],$group=''){
        $conditions = "order_type=0";
        if(isset($data['order_create_time']) && !empty($data['order_create_time'])){
            $conditions .= " AND order_create_time>='{$data['order_create_time']['start_at']}' AND  order_create_time<='{$data['order_create_time']['end_at']}'";
        }
        if(isset($data['referer_ids']) && !empty($data['referer_ids'])){
            $conditions .= " AND user_id in({$data['referer_ids']})";
        }

        if($group){
            $sql_params=[
                $conditions,
                'columns'=>'id',
                'group'=>$group,
            ];
            $order_count = $this->find($sql_params)->toarray();
            return count($order_count);

        }else{
            $sql_params=[
                $conditions,
                'columns'=>'id',
                'limit'=>1,
            ];
            $order_count = $this->count($sql_params);
        }

        return $order_count;
    }




    /**
     * 数据插入
     * 1插入 2更新
     */
    public function unionOrderInsert($column, $data)
    {
        $ridToUserIdChannelId = $this->tAUserExtend->ridMappingUserId($column, array_column($data, 'rid'));
        $databaseOrder = $this->orderNoDb($data);           //数据库中存在的订单

        $revenuesRateDi = $this->dictionary->getByGroupList(8);  //扣税

        foreach ($data as $key => $value) {
            if (isset($databaseOrder[$value['orderId']])) {           //存在订单
                if ($this->updateOrderBean($databaseOrder[$value['orderId']], $value)) {

                    $revenuesAmount = $this->revenuesRate($value['rebateAmount'], $value['orderSrc'], $revenuesRateDi);      //获取扣税

                    $responseResult = $this->where("order_no", $value['orderId'])->first();

                    $responseResult->trade_amount = $value['payMoney'] * 100;

                    if(!in_array($value['orderStatus'],[3,5,11]) || $databaseOrder[$value['orderId']]['income_amount'] == 0) {
                        $responseResult->settle_amount = $value['rebateAmount'] * 100;//isset($value['rebateAmount']) && !empty($value['rebateAmount']) ? $value['rebateAmount'] * 100 : $databaseOrder[$value['orderId']]['settle_amount'];
                        $responseResult->income_amount = $revenuesAmount['income_amount'];//isset($revenuesAmount['income_amount']) && !empty($revenuesAmount['income_amount']) ? $revenuesAmount['income_amount'] : $databaseOrder[$value['orderId']]['income_amount'];        //扣税之后结算给用户的金额
                        $responseResult->revenues_rate = $revenuesAmount['revenues'];//isset($revenuesAmount['revenues']) && !empty($revenuesAmount['revenues']) ? $revenuesAmount['revenues'] : $databaseOrder[$value['orderId']]['revenues_rate'];                          //后台当年设置的税金比例
                        $responseResult->tax_amount = $revenuesAmount['tax_amount'];//isset($revenuesAmount['tax_amount']) && !empty($revenuesAmount['tax_amount']) ? $revenuesAmount['tax_amount'] : $databaseOrder[$value['orderId']]['tax_amount'];                               //扣税之后的金额
                        $responseResult->tag = 1;
                    }

                    $responseResult->updated = date("Y-m-d H:i:s");
                    $responseResult->trade_time = $value['orderPaidTime'];
                    $responseResult->earning_time = $value['orderEarningTime'];
                    $responseResult->order_created_time = $value['orderCreateTime'];
                    if ($databaseOrder[$value['orderId']]['order_type'] == 3 || (isset($value['isPunish']) && $value['isPunish'])) {       //违规订单
                        $value['orderType'] = 3;
                    }
                    $responseResult->settle_status = ($databaseOrder[$value['orderId']]['settle_status'] == 3) ? 3 : $this->settlementStatus($value['orderStatus'],$databaseOrder[$value['orderId']]['order_type']); //订单结算状态为已结算则不修改
                    $responseResult->order_type = in_array($databaseOrder[$value['orderId']]['order_type'],[2,3]) ? $databaseOrder[$value['orderId']]['order_type'] : $value['orderType'];   //订单是违规和维权订单，不改变原来的属性
                    $responseResult->order_status = ($value['orderType'] == 3 || in_array($databaseOrder[$value['orderId']]['order_type'],[2,3])) ? $databaseOrder[$value['orderId']]['order_status'] : $value['orderStatus'];           //如果订单为违规订单，则失效
                    if ($responseResult->save()) {
//                        var_dump("更新成功{$value['orderId']}");
                    } else {
//                        var_dump("更新失败{$value['orderId']}");
                    }
                }
            } else {
                $TUnionOrdeDb = new TUnionOrder();
                $TUnionOrdeDb->order_no = $value['orderId'];
                $TUnionOrdeDb->user_id = isset($ridToUserIdChannelId[$value['rid']]['user_id']) ? $ridToUserIdChannelId[$value['rid']]['user_id'] : 0;
                $TUnionOrdeDb->channel_id = isset($ridToUserIdChannelId[$value['rid']]['channel_id']) ? $ridToUserIdChannelId[$value['rid']]['channel_id'] : 0;
                $TUnionOrdeDb->order_src = $value['orderSrc'];
                $TUnionOrdeDb->order_status = $value['orderStatus'];
                $TUnionOrdeDb->order_type = $value['orderType'];
                $TUnionOrdeDb->goods_id = $value['goodsId'];
                $TUnionOrdeDb->src_item = $value['tagItem'];
                $TUnionOrdeDb->settle_status = $this->settlementStatus($value['orderStatus']);
                $TUnionOrdeDb->trade_amount = $value['payMoney'] * 100;
                $TUnionOrdeDb->settle_amount = $value['rebateAmount'] * 100;

                $revenuesAmount = $this->revenuesRate($value['rebateAmount'], $value['orderSrc'], $revenuesRateDi);      //扣税金额

                $TUnionOrdeDb->revenues_rate = $revenuesAmount['revenues'];                         //后台当前设置的税金比例
                $TUnionOrdeDb->tax_amount = $revenuesAmount['tax_amount'];                              //扣税之后的金额
                $TUnionOrdeDb->income_amount = $revenuesAmount['income_amount'];        //扣税之后结算给用户的金额
                $TUnionOrdeDb->old_income_amount = $revenuesAmount['income_amount'];        //扣税之后结算给用户的金额

                $TUnionOrdeDb->name = $value['name'];
                if ($value['images']) {
                    $value['images'] = strpos($value['images'], 'http') !== false ? $value['images'] : "https:{$value['images']}";
                } else {
                    $value['images'] = "";
                }
                $TUnionOrdeDb->images = $value['images'];
                $TUnionOrdeDb->created = date("Y-m-d H:i:s");
                $TUnionOrdeDb->updated = date("Y-m-d H:i:s");
                $TUnionOrdeDb->trade_time = $value['orderPaidTime'];
                $TUnionOrdeDb->earning_time = $value['orderEarningTime'];
                $TUnionOrdeDb->order_created_time = $value['orderCreateTime'];
                $TUnionOrdeDb->shop_name = isset($value['shopName']) ? $value['shopName'] : $value['shopName'];

                $order_count = isset($ridToUserIdChannelId[$value['rid']]['user_id']) && $value['goodsId'] ? $this->orderGoodsCount($ridToUserIdChannelId[$value['rid']]['user_id'], $value['goodsId']) : 0;
                $TUnionOrdeDb->order_count = $order_count;

                if ($TUnionOrdeDb->save()) {

                    if (isset($ridToUserIdChannelId[$value['rid']]['user_id']) && !empty($ridToUserIdChannelId[$value['rid']]['user_id']) && $value['payMoney'] > 1 && $value['orderStatus'] > 1) {
                        try {
                            $UserService = new UserServiceImpl();
                            $UserService->userShopping($ridToUserIdChannelId[$value['rid']]['user_id']);
                        } catch (\Exception $e) {

                        }
                    }

//                    var_dump("插入成功{$value['orderId']}");
                } else {
//                    var_dump("插入失败{$value['orderId']}");
                }
            }
        }
        return true;
    }


    /**
     * 违规订单订单处理
     */
    public function weiguiOrderDeal($requestData=[]){
        $databaseOrder = $this->orderNoDb($requestData);           //数据库中存在的订单
        foreach($requestData as $key=>$value){
            if(isset($databaseOrder[$value['orderId']])){
                if($this->weiguiOrderBean($databaseOrder[$value['orderId']],$value)){           //判断库里面的订单类型是否一致，不一致则更新
                    $responseResult = $this->where("order_no", $value['orderId'])->first();
                    $responseResult->order_type = $value['orderType'];
                    $responseResult->settle_status = $databaseOrder[$value['orderId']]['settle_status'] == 3 ? 3 : 4;           //如果已经结算了，就不设置失效订单
                    $responseResult->order_status = $value['orderStatus'];
                    $responseResult->remark = "{$databaseOrder[$value['orderId']]['remark']}|下单时间:{$value['orderCreateTime']},违规类型:{$value['remark']}|";
                    if ($responseResult->save()) {
//                        var_dump("失效订单更新成功{$value['orderId']}");
                    } else {
//                        var_dump("失效订单更新失败{$value['orderId']}");
                    }
                }
            }
        }
    }



    /**
     * 维权订单订单处理
     */
    public function weiquanOrderDeal($requestData=[]){
        $databaseOrder = $this->orderNoDb($requestData);           //数据库中存在的订单
        foreach($requestData as $key=>$value){
            if(isset($databaseOrder[$value['orderId']])){
                if($this->weiguiOrderBean($databaseOrder[$value['orderId']],$value)){           //判断库里面的订单类型是否一致，不一致则更新
                    $responseResult = $this->where("order_no", $value['orderId'])->first();
                    $responseResult->order_type = $value['orderType'];
                    $responseResult->settle_status = $databaseOrder[$value['orderId']]['settle_status'] == 3 ? 3 : $this->settlementStatus($value['orderStatus'],$databaseOrder[$value['orderId']]['order_type']);           //如果已经结算了，就不设置失效订单
                    $responseResult->order_status = $value['orderStatus'];
                    $responseResult->remark = "{$databaseOrder[$value['orderId']]['remark']}|维权时间:{$value['refundTime']}|维权信息:{$value['remark']}";
                    if ($responseResult->save()) {
//                        var_dump("维权更新成功{$value['orderId']}");
                    } else {
//                        var_dump("维权更新失败{$value['orderId']}");
                    }
                }
            }
        }
    }



    /**
     * 违规订单判断
     */
    public function weiguiOrderBean($databaseData,$platment)
    {
        if($platment['orderType'] == 3){
            return false;
        }
        if ($platment['orderType'] != $databaseData['order_type']) {  //订单状态
            return true;
        }
        if($platment['orderStatus'] != $databaseData['order_status']){
            return true;
        }
        return false;
    }



    /**
     * 更新的时候判断 第三方回来的佣金是否和库里面的佣金相同
     */
    public function updateOrderBean($databaseData, $platment)
    {
        $commition = (int)($platment['rebateAmount'] * 100);
        if ($commition != $databaseData['settle_amount']) {        //支付金额不一样
            return true;
        }

        $payMoney = (int)($platment['payMoney'] * 100);
        if ($payMoney != $databaseData['trade_amount']) {         //交易金额
            return true;
        }

        if ($platment['orderStatus'] != $databaseData['order_status']) {  //订单状态
            return true;
        }

        return false;
    }


    /**
     * 结算状态
     */
    public function settlementStatus($orderStatus,$orderType=0)
    {
        if($orderType == 3){
            return 4;
        }
        if (in_array($orderStatus, [1, 3, 5, 11])) {
            return 4;
        } else {
            if (in_array($orderStatus, [2, 4, 6])) {
                return 2;
            }
        }
        return 1;
    }


    /**
     * 扣税比例
     * @param $commition    第三方回来的订单佣金
     * @param $src      平台 1.淘宝 2.京东 3.拼多多 4.唯品会 5.苏宁 6美团
     * @param $revenues 每个平台的税金比例
     */
    public function revenuesRate($commition, $src, $revenues)
    {
        $commition = (int)($commition * 100);
        $responseResult = ['revenues' => 0, 'tax_amount' => 0, 'income_amount' => 0];
        switch ($src) {
            case 1:
                $tax_amount = $revenues['taobao_revenues'] ? $commition * ($revenues['taobao_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['taobao_revenues'];
                break;
            case 2:
                $tax_amount = $revenues['jd_revenues'] ? $commition * ($revenues['jd_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['jd_revenues'];
                break;
            case 3:
                $tax_amount = $revenues['pdd_revenues'] ? $commition * ($revenues['pdd_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['pdd_revenues'];
                break;
            case 4:
                $tax_amount = $revenues['vph_revenues'] ? $commition * ($revenues['vph_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['vph_revenues'];
                break;
            case 5:
                $tax_amount = $revenues['sn_revenues'] ? $commition * ($revenues['sn_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['sn_revenues'];
                break;
            case 6:
                $tax_amount = $revenues['taobao_revenues'] ? $commition * ($revenues['taobao_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['taobao_revenues'];
                break;
            case 7:
                $tax_amount = $revenues['mt_revenues'] ? $commition * ($revenues['mt_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['mt_revenues'];
                break;
            case 8:
                $tax_amount = $revenues['mt_revenues'] ? $commition * ($revenues['mt_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['mt_revenues'];
                break;
            case 9:
                $tax_amount = $revenues['mt_revenues'] ? $commition * ($revenues['mt_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['mt_revenues'];
                break;
            case 10:
                $tax_amount = $revenues['mt_revenues'] ? $commition * ($revenues['mt_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['mt_revenues'];
                break;
            case 11:
                $tax_amount = $revenues['jutuike_revenues'] ? $commition * ($revenues['jutuike_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['jutuike_revenues'];
                break;
            case 12:
                $tax_amount = $revenues['haodanku_dy_revenues'] ? $commition * ($revenues['haodanku_dy_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['haodanku_dy_revenues'];
                break;
            case 13:
                $tax_amount = $revenues['meituan_tuangou_revenues'] ? $commition * ($revenues['meituan_tuangou_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['meituan_tuangou_revenues'];
                break;
            case 14:
                $tax_amount = $revenues['meituan_miaosha_revenues'] ? $commition * ($revenues['meituan_miaosha_revenues'] / 100) : 0;
                $responseResult['revenues'] = $revenues['meituan_miaosha_revenues'];
                break;
        }
        $responseResult['income_amount'] = (int)($commition - $tax_amount);
        $tax_amount = $commition - $responseResult['income_amount'];
        $responseResult['tax_amount'] = (int)$tax_amount;
        return $responseResult;
    }


    /**
     * 根据用户获取用户是否授信息
     */
    public function getOrderNo(string $orderNo)
    {
        $data = $this
            ->select()
            ->where('order_no', $orderNo)
            ->first();
        if ($data) {
            return $data->toArray();
        }
        return [];
    }


    /**
     * 根据订单号查找订单
     */
    public function findUserOrder($user_id, $order_no)
    {
        $data = $this
            ->select()
            ->where('order_no', $order_no)
            ->first();
        if (!$data) {
            return ['status' => false, 'msg' => '没有找到订单'];
        }
        $data = $data->toArray();
        if ($data['user_id'] != 0) {
            return ['status' => false, 'msg' => '该订单不能找回'];
        }
        $responseResult = $this->where("order_no", $order_no)->update(['user_id' => $user_id]);
        if ($responseResult) {
            return ['status' => true, 'msg' => '找回成功'];
        } else {
            return ['status' => false, 'msg' => '找回失败'];
        }
    }


    /**
     * 根据订单号查找订单
     */
    public function findUserOrderSearch($user_id, $order_no)
    {
        $data = $this
            ->select()
            ->where('order_no', $order_no)
            ->first();
        if (!$data) {
            return ['status' => false, 'msg' => '没有找到订单'];
        }
        $data = $data->toArray();
        if ($data['user_id'] != 0) {
            return ['status' => false, 'msg' => '该订单不能找回'];
        }
        $result['originPrice'] = $data['trade_amount'];
        $result['name'] = $data['name'];
        $result['image'] = $data['images'];
        $result['orderCreatedTime'] = $data['order_created_time'];
        return ['status' => true, 'data' => $result];
    }


    /**
     * 通过订单号集合查找订单
     */
    public function orderNoDb($orderNoArr)
    {
        $orderNoArray = array_column($orderNoArr, 'orderId');
        $orderListArr = $this
            ->select()
            ->whereIn('order_no', $orderNoArray)
            ->get()
            ->toArray();
        if ($orderListArr) {
            $responseResult = [];
            foreach ($orderListArr as $key => $value) {
                $responseResult[$value['order_no']] = $value;
            }
            return $responseResult;
        } else {
            return [];
        }
    }


    /**
     * 统计用户最近七天对同一个商品下单次数
     */
    public function orderGoodsCount($user_id, $goods_id)
    {
        if ($user_id < 0) {
            return 0;
        }
        $currentSevenDay = timeChange(3);
        $sql = "SELECT COUNT(goods_id) AS count FROM `t_union_order` WHERE user_id={$user_id} AND goods_id='{$goods_id}' AND (order_created_time >= '{$currentSevenDay['start_at']}' and order_created_time <= '{$currentSevenDay['end_at']}' )";
        $count = Db::selectOne($sql);
        return isset($count->count) ? (int)$count->count + 1 : 1;
    }



}
